package com.wkw.jkyf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wkw.jkyf.mapper.UserMapper;
import com.wkw.jkyf.pojo.Supplier;
import com.wkw.jkyf.pojo.User;
import com.wkw.jkyf.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
用户Service实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public User queryUserByUserName(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        return userMapper.selectOne(wrapper);
    }

    @Override
    //分页查询
    public IPage<User> selectUserPage(int pageNum, int pageSize, String param) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(param)){
            queryWrapper.like("username",param);
        }
        Page<User> page = new Page<>();
        return userMapper.selectPage(page,queryWrapper);
    }

    @Override
    @Transactional
    //添加用户
    public int addUser(User user) {
        String phone = user.getPhone();
        //通过正则表达式规范手机号
        Pattern pattern = Pattern.compile("^[1][1-9]{1}[0-9]{9}");
        Matcher isMatcher = pattern.matcher(phone);
        if(isMatcher.matches()){
          return userMapper.insert(user);
        }
        return -3;
    }

    @Override
    public int editUser(User user) {
        return userMapper.updateById(user);
    }

    @Override
    public User queryUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public int deleteUserById(Integer id) {
        return userMapper.deleteById(id);
    }

    @Override
    public List<User> queryUserList() {
        return userMapper.selectList(null);
    }
}
